import os
from tqdm import tqdm  # 进度条显示[1](@ref)
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO

def download_image_from_pexels(keyword, api_key):
    url = "https://api.pexels.com/v1/search"
    headers = {"Authorization": api_key}
    params = {"query": keyword, "per_page": 1}
    response = requests.get(url, headers=headers, params=params)
    photo_url = response.json()['photos'][0]['src']['large']
    img_data = requests.get(photo_url).content
    return Image.open(BytesIO(img_data))

def get_img_by_en_from_pexels(words, dir_path):
    os.makedirs('output', exist_ok=True)
    for word_pair in tqdm(words, desc="进度"):
        try:
            img = download_image_from_pexels(word_pair['en_word'], "1V4UKRH2kBjgF2YjiRSsF6dU41jBMM5qCJ013jJgGMVr5qTxkwC6R6o1")
            print('find image for word "' + word_pair['cn_word'] + '"')
            img.save(dir_path + '/' + word_pair['cn_word'] + '.jpg')
        except Exception as e:
            print(f"生成失败：{word}，错误：{str(e)}")

def get_img_only_by_en_from_pexels(en_words, dir_path):
    os.makedirs('output', exist_ok=True)
    for en_word in tqdm(en_words, desc="进度"):
        try:
            img = download_image_from_pexels(en_word, "1V4UKRH2kBjgF2YjiRSsF6dU41jBMM5qCJ013jJgGMVr5qTxkwC6R6o1")
            print('find image for word "' + en_word + '"')
            img.save(dir_path + '/' + en_word + '.jpg')
        except Exception as e:
            print(f"生成失败：{en_word}，错误：{str(e)}")